<!-- 实习评价模板页面 -->
<template>
  <ContentCard>
    <template #header>
      <PageHeaderNew
        :title="title"
        :breadCrumb="breadCrumb"
        :isShowBtn="true"
        show-back
      >
      </PageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20" class="box">
      <template #left>
        <a-input-search
          v-model="nameSearch"
          placeholder="请输入模板名称，按下回车可以搜索"
          :style="{
            width: '300px'
          }"
          search-button
          @search="onSearch"
          @press-enter="onSearch"
        >
          <icon-search />
        </a-input-search>
      </template>

      <template #right>
        <a-button type="primary" @click="add">新增模板</a-button>
        <a-button type="outline" @click="del(null)" status="danger"
          >批量删除</a-button
        >
      </template>
    </ConditionBox>
    <TableTurn
      ref="tableRef"
      :tableData="getTableData"
      :args="args"
      style="margin-top: 20px"
    >
      <a-table-column :width="80">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column :width="150" title="评价模板名称" dataIndex="name">
      </a-table-column>
      <a-table-column :width="150" title="评价总分" dataIndex="upperValue">
      </a-table-column>
      <a-table-column :width="150" title="描述" dataIndex="remark">
      </a-table-column>
      <!-- <a-table-column :width="150" title="创建人" dataIndex="remark">
        <template #cell="{ record }">
          {{ record.organizationTemplateModel.remark }}
        </template>
      </a-table-column>
      <a-table-column :width="150" title="创建时间" dataIndex="remark">
        <template #cell="{ record }">
          {{ record.organizationTemplateModel.remark }}
        </template>
      </a-table-column> -->
      <a-table-column
        title="是否启用"
        data-index="status"
        align="center"
        :width="100"
      >
        <template #cell="{ record: { enable } }">
          <a-tag
            class="enable"
            :color="
              enable === 1 ? `rgb(var(--green-1))` : 'rgb(var(--danger-1))'
            "
            :style="{
              color:
                enable === 1 ? `rgb(var(--green-6))` : 'rgb(var(--danger-6))',
              '--enable':
                enable === 1 ? `rgb(var(--green-6))` : 'rgb(var(--danger-6))'
            }"
          >
            {{ enable === 1 ? '启用' : '停用' }}
          </a-tag>
        </template>
      </a-table-column>
      <a-table-column :width="100" title="是否为默认模板" dataIndex="required">
        <template #cell="{ record }">
          <a-switch
            :checked-value="1"
            :unchecked-value="2"
            v-model="record.default"
            @change="stateChange(record)"
          />
        </template>
      </a-table-column>
      <a-table-column title="操作" :width="100" fixed="right">
        <template #cell="{ record }">
          <a-space :size="0">
            <a-tooltip content="预览">
              <icon-eye
                :size="26"
                @click="goPreview(record)"
                style="color: #5085ff; cursor: pointer"
              />
            </a-tooltip>
            <a-tooltip content="复制">
              <IconFont
                type="icon-fuzhi"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goCopy(record)"
              />
            </a-tooltip>
            <a-tooltip content="编辑">
              <IconFont
                type="icon-edit"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goEdit(record)"
              />
            </a-tooltip>
            <a-tooltip content="删除" position="left">
              <a-popconfirm content="是否确认删除该条数据?" @ok="del(record)">
                <IconFont
                  type="icon-delete"
                  :size="26"
                  :style="{
                    cursor: 'pointer'
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
          </a-space>
        </template>
      </a-table-column>
    </TableTurn>

    <!-- <FormTemplate
      ref="templateRef"
      :data="currRecord.data"
      :fn="tableRef"
      :title="`实习评价模板`"
    ></FormTemplate> -->
  </ContentCard>

  <TemplateDesign
    title="实习评价模板"
    ref="showTemplate"
    type="editShow"
    :id="formData.id"
    @saveForm="save"
    :refForm="refForm"
    :back="back"
    :isShowRenderTemplate="false"
  >
    <template #base>
      <a-form
        :model="formData.data"
        layout="vertical"
        :rules="rules"
        ref="refForm"
      >
        <a-form-item field="name" label="实习评价模板名称" show-colon required>
          <a-input
            size="large"
            v-model="formData.data.name"
            placeholder="请输入模板名称"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="enable" label="启用状态" show-colon>
          <a-switch
            v-model="formData.data.enable"
            :checked-value="1"
            :unchecked-value="2"
          />
        </a-form-item>
        <a-form-item field="remark" label="描述" show-colon>
          <a-textarea
            v-model="formData.data.remark"
            placeholder="请输入"
            show-word-limit
            :max-length="300"
            :auto-size="{
              minRows: 5
            }"
            allow-clear
          />
        </a-form-item> </a-form
    ></template>
    <template #template-design>
      <FormSetting
        ref="formSettigRef"
        v-model:data="formData.data"
      ></FormSetting>
    </template>
  </TemplateDesign>
  <PreviewModal v-model:visible="previewVisible" :data="currData" />
  <CopyModal
    v-model:visible="copyVisible"
    @copy-emit="copyEmit"
    @copyEditEmit="copyEditEmit"
    :validateFun="validateNameToCopy"
  />
</template>

<script lang="ts" setup>
/* eslint-disable */
import {
  GetInternshipEvaluationList,
  PostInternshipEvaluationList,
  PutInternshipEvaluationTemplateState,
  DelInternshipEvaluationList,
  GetInternshipEvaluationDetail,
  PutInternshipEvaluationList,
  CheckInternshipEvaluationList,
  PutInternshipEvaluationTemplateShow
} from '@/apis/management/human/baseSetting/internshipSetting/index';
import { GetBusinessModalData } from '@/apis/controltotal/index';
// import { GetControl } from '@/apis/management/base';
import { useSetupFormStore } from '@/store';
import { Message, Modal } from '@arco-design/web-vue';
import { cloneDeep } from 'lodash';
import { changeControlData } from '@/utils/control';
import { validateRules } from '@/utils/common';
import FormSetting from './FromSetting/index.vue';
import PreviewModal from './Components/Preview/index.vue';

const name = useRoute().query.name; // 组织类型名字
const breadCrumb = ['人事', '基础设置', '实习期设置', `实习评价信息模板`];
const title = `实习评价模板`;
const store = useSetupFormStore();
// 选择器配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
});
let tableRef = ref();
let formSettigRef = ref();
let showTemplate = ref();
let nameSearch = ref();
const businessType = ref(['SER_FUNC113244100', 'baseComponent']);
let singleSelectId = 0; // 储存单个id
/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);
const selectedListData = computed(() => tableRef.value.selectedListData);

let refForm = ref();

const validateName = async (val: string, cb: any) => {
  try {
    if (formData.data?.id && preName == val) {
      //
    } else {
      const res = await CheckInternshipEvaluationList({
        name: val
      });
      if (res.code) cb(`${res.msg}`);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

const validateNameToCopy = async (name: string, cb: any) => {
  try {
    if (formData.data?.id && preName === name) {
      //
    } else {
      const data = {
        name
      };
      const res = await validateRules(CheckInternshipEvaluationList, data);
      return Promise.resolve(res);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

const rules = {
  name: [
    {
      required: true,
      message: '请输入模板名称'
    },
    {
      validator: validateName
    }
  ],
  enable: [
    {
      required: true,
      message: '请选择启用状态'
    }
  ]
};
// 储存模板所有数据
const formData: any = reactive({
  data: {
    name: '',
    enable: 1,
    remark: '',
    organizationEvaluation: 100,
    selfEvaluation: 0,
    upperLimitType: 2,
    scoreCalculation: 1,
    indexArr: [], // 指标表格
    customArr: [] // 自定义表格
  }
});

let originData = cloneDeep(formData.data); // 储存原始数据
// 获取列表信息
const getTableData = async (pageData?: any) => {
  const res = await GetInternshipEvaluationList({
    // id: ID,
    name: nameSearch.value,
    ...pageData
    // patternId: id
  });
  originData.value = cloneDeep(res.content);
  // temp.content = res.content[0].organizationTemplateModel;

  return Promise.resolve(res);
};

const onSearch = () => {
  refresh();
};

// 点击新增模板按钮
const add = () => {
  formData.data = cloneDeep(originData);
  showTemplate.value.fullScreen();
};
const templateData: any = reactive({ data: [] });
const init = async () => {
  const res = await GetBusinessModalData({ funcCode: 'SER_FUNC113244100' });
  templateData.data = res?.funcCtlInfos
    ? changeControlData(res.funcCtlInfos, 'tableHead')
    : null;
  console.log('console.log(templateData.data);', templateData.data);
};

init();

// 修改模板默认状态
const stateChange = async (record: any) => {
  try {
    if (record.default === 2) Message.error('必须拥有一个默认模板！');
    else
      await PutInternshipEvaluationTemplateState({
        id: record.id
      });
    refresh();
  } catch (error: unknown) {
    console.log(error);
  }
};

let previewVisible = ref(false);
const goPreview = (record: any) => {
  currData.value = record;
  previewVisible.value = true;
};

let preName = ''; //  储存修改之前的名字
// 编辑页面
const goEdit = async (record: any, name?: string) => {
  try {
    formData.data = record;
    preName = record.name;
    if (name) {
      preName = name;
      formData.data.name = name;
      formData.data = delId(formData.data);
      console.log('======================formDataformData==============');
      console.log(formData.data);
      console.log('====================================');
    }
    showTemplate.value.fullScreen();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 删除
const del = async (record: any) => {
  try {
    if (!record) {
      if (selectedList.value.length === 0) {
        Message.error('请至少选择一项！');
      } else {
        Modal.confirm({
          title: '提示',
          content: '确定要删除选中的数据吗？',
          onOk: async () => {
            try {
              if (
                selectedListData.value.find((item: any) => item.default === 1)
              ) {
                Message.error('默认模板不能删除！');
              } else {
                await DelInternshipEvaluationList({
                  ids: selectedList.value,
                  type: 1
                });
                tableRef.value.selectedList = [];
                refresh();
              }
            } catch (error: unknown) {
              console.log(error);
            }
          }
        });
      }
    } else {
      if (record.default === 1) Message.error('默认模板不能删除！');
      else {
        await DelInternshipEvaluationList({
          ids: [record.id],
          type: 1
        });
        tableRef.value.selectedList = [];
        refresh();
      }
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

let copyVisible = ref(false);
let currData = ref();
// 显示复制弹窗
const goCopy = (record: any) => {
  copyVisible.value = true;
  currData.value = record;
};
// // 复制
const copyEmit = async (record: any) => {
  try {
    currData.value.name = record.name;
    currData.value.default = 2;
    currData.value = delId(currData.value);
    await PostInternshipEvaluationList(currData.value);
    refresh();
    console.log(record);
  } catch (error: unknown) {
    console.log(error);
  }
};

const copyEditEmit = (record: any) => {
  goEdit(currData.value, record.name);
};

// 删除id
const delId = (formData: any) => {
  formData.indexArr.forEach((el: any) => {
    delete el.id;
  });
  formData.customArr.forEach((el: any) => {
    delete el.id;
  });
  delete formData.id;
  delete formData.createdAt;
  return formData;
};

const save = async () => {
  formData.data.customArr.forEach((item: any) => {
    if (item.name === '') {
      Message.error('自定义指标名称不能为空');
      return;
    }
  });
  if (formData.data.id) {
    if (formSettigRef.value.delTypeIds.type2Ids.length > 0) {
      await DelInternshipEvaluationList({
        ids: formSettigRef.value.delTypeIds.type2Ids,
        type: 2
      });
    }
    if (formSettigRef.value.delTypeIds.type3Ids.length > 0) {
      await DelInternshipEvaluationList({
        ids: formSettigRef.value.delTypeIds.type3Ids,
        type: 3
      });
    }
    await PutInternshipEvaluationList(formData.data);
  } else await PostInternshipEvaluationList(formData.data);
  refresh();
};

const refresh = () => {
  tableRef.value.loadData();
};
</script>

<style scoped lang="less">
.enable::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: relative;
  right: 3px;
  background-color: var(--enable);
}
</style>
